package com.example.spring.mono.service.impl;

import com.example.spring.mono.entity.Order;
import com.example.spring.mono.repository.OrderRepository;
import com.example.spring.mono.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Override
    public Mono<Order> saveOrder(Order order) {
        return orderRepository.save(order);
    }

    @Override
    public Flux<Order> getAll() {
        return orderRepository.findAll();
    }


    @Override
    public Mono<ResponseEntity<Order>> findOrderByOrderNo(String orderNo) {
        return orderRepository.findById(orderNo)
                // 用户存在返回200和用户信息
                .map(order -> new ResponseEntity<>(order, HttpStatus.OK))
                // 不存在则返回404
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @Override
    public Mono<ResponseEntity<Void>> delOrderByOrderNo(String orderNo) {

       /* return userRepository.findById(id).flatMap(user -> userRepository.delete(user)
                // 用户存在，删除成功
                .then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK))))
                // 用户不存在，删除失败
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));*/

        return orderRepository.findById(orderNo).flatMap(order ->orderRepository.delete(order))
                .then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK)))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
}
